package john.walker.jmx;

import java.lang.management.ManagementFactory;

import javax.management.InstanceAlreadyExistsException;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;

/**
 *
 * @author Johnnie Walker
 *
 */
public class JMXUtils {

	/**
	 * @param name
	 * @param mbean
	 * @return
	 */
	public static ObjectName register(String name, Object mbean) {
		try {
			ObjectName objectName = new ObjectName(name);

			MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();

			try {
				mbeanServer.registerMBean(mbean, objectName);
			} catch (InstanceAlreadyExistsException ex) {
				mbeanServer.unregisterMBean(objectName);
				mbeanServer.registerMBean(mbean, objectName);
			}

			return objectName;
		} catch (JMException e) {
			throw new IllegalArgumentException(name, e);
		}
	}

	/**
	 * @param name
	 */
	public static void unregister(String name) {
		try {
			MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();

			mbeanServer.unregisterMBean(new ObjectName(name));
		} catch (JMException e) {
			throw new IllegalArgumentException(name, e);
		}

	}
}
